import random

from django import http
from django_redis import get_redis_connection
# Create your views here.
from django.views import View
from users.models import User

from celery_tasks.sms.tasks import send_sms_code
from meiduo.libs.captcha.captcha import captcha
#captcha.generate_captcha()
from celery_tasks.sms.yuntongxun.sms import CCP
#   CCP().send_template_sms('15301387', ['123456', 5], 1)
from meiduo.utils.response_code import RETCODE


class ImageCodeView(View):
    def get(self,request,uuid):
        k,image_code,img=captcha.generate_captcha()
        # 连接redis
        conn = get_redis_connection("SMSCODE")
        # 设置过期时间
        conn.setex(uuid,300,image_code)
        return http.HttpResponse(img,content_type='img/png')
#/?image_code=' + this.image_code + '&uuid=' + this.uuid;
class SMSCodeView(View):
    def get(self,request,mobile):
        # 连接数据库，并且查看60秒内是否已经发送过了短信
        conn = get_redis_connection("SMSCODE")
        if conn.get("sms_mobile%s"%mobile):
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '频繁发送短信'})

        ImgCodeVerifyData = request.GET
        uuid = ImgCodeVerifyData.get("uuid")

        image_code=ImgCodeVerifyData.get("image_code")


        if not all([uuid,image_code]):
            return http.HttpResponse("你数据不齐全")

        # mobile2 = User.objects.filter(mobile=mobile).count()
        # if mobile2 >0:
        #     return http.HttpResponse("不好意思，您输入的手机已经存在，请登录")
        # # 获取数据库里面的验证码SMSCODE

        image_code2 = conn.get(uuid).decode()
        conn.delete(uuid)
        if image_code2 is  None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码已过期'})
        if image_code2.lower() != image_code.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码输入错误'})
        SmsCode = random.randint(0,999999)
        print(mobile,SmsCode)
        # 存入redis使用管道
        pl = conn.pipeline()
        pl.setex(mobile,300,SmsCode)
        pl.setex("sms_mobile%s"%mobile,60,SmsCode)
        pl.execute()
        # 使用celery进程异步处理发送请求
    #TODO celery 使用
        send_sms_code.delay(mobile,SmsCode)
        # CCP().send_template_sms(mobile, ['%06d'%SmsCode, 5], 1)
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


